package com.yotoodesign.dianba.fragment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.yotoodesign.core.util.LoadDataAsynTask;
import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.adapter.MySongAdapter;
import com.yotoodesign.dianba.adapter.SongListAdapter;
import com.yotoodesign.dianba.app.GlobalApplication;
import com.yotoodesign.dianba.bean.Album;
import com.yotoodesign.dianba.bean.Song;
import com.yotoodesign.dianba.bean.SongList;
import com.yotoodesign.dianba.bean.SongListGroupArray;
import com.yotoodesign.dianba.custom.CustomDialog;
import com.yotoodesign.dianba.ui.DialogUtil;
import com.yotoodesign.dianba.ui.IDialogCallback;
import com.yotoodesign.dianba.ui.MainActivity;
import com.yotoodesign.dianba.util.Constant;
import com.yotoodesign.dianba.util.WeiboConstant;


public class MyFragment extends BaseFragment implements IDialogCallback{

	ListView mylist;
	ExpandableListView listAll;
	
	MySongAdapter mySongAdapter;
	SongListAdapter songListAdapter;
	SongListGroupArray array;
	
	boolean editing = false;
	String currentKey = "";//当前编辑的点歌单key
	String currentName = "";//当前编辑的点歌单名称
	String currentDesc = "";//当前编辑的点歌单描述
	
	boolean isCreateView = true;//是否创建视图时
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View view =  inflater.inflate(R.layout.my_fragment, container,false);
		final TextView mainTitle = (TextView)view.findViewById(R.id.mainTitle);
		mainTitle.setText(R.string.mylist);
		ImageButton commonBack = (ImageButton)view.findViewById(R.id.commonBack);
		commonBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GlobalApplication.getMainActivity().goHome();
			}
		});
		
		//获取数据：我的点歌列表
		final MainActivity main = GlobalApplication.getMainActivity();
		
		final Button btnOk = (Button)view.findViewById(R.id.btnOk);
		btnOk.setVisibility(View.VISIBLE);
		btnOk.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mySongAdapter.getSongList()==null || mySongAdapter.getSongList().size()==0){
					Toast.makeText(getActivity(), "点歌单还是空的哦，先去点歌吧！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				//如果是编辑状态，则直接保存
//				if(editing){
//					GlobalApplication.getInstance().saveAsList(currentKey,getSongList(), 
//							currentName, currentDesc);
//					//刷新显示数据
//					reloadList();
//					return;
//				}
				
				//保存点歌单
				View save_list = LayoutInflater.from(getActivity()).inflate(R.layout.save_list, null);
				final EditText etListName = (EditText)save_list.findViewById(R.id.etListName);
				final EditText etListDesc = (EditText)save_list.findViewById(R.id.etListDesc);
				
				
				final PopupWindow pop = new PopupWindow(save_list,ViewGroup.LayoutParams.MATCH_PARENT, 
						ViewGroup.LayoutParams.MATCH_PARENT,true);
				pop.setOutsideTouchable(true);
				pop.setFocusable(true);
				pop.setOnDismissListener(addDismissListener());
				pop.update();
				pop.showAtLocation(v, Gravity.CENTER, 0, 0);
				
				//保存到原点歌单中
				Spinner oldList = (Spinner)save_list.findViewById(R.id.oldList);
				oldList.setPrompt("选择点歌单");
				
				List<String> oldListAry=new ArrayList<String>();
				
				for(Iterator<Album> it = main.getMySongList().iterator();it.hasNext();){
					Album album = (Album)it.next();
					oldListAry.add(album.getName());
				}
				
				ArrayAdapter<String> adapter =new ArrayAdapter<String>(getActivity(),  
						 android.R.layout.simple_spinner_item,oldListAry);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				oldList.setAdapter(adapter); 
				oldList.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						Album album = main.getMySongList().get(position);
						GlobalApplication.getInstance().saveAsList(album.getId(),getSongList(), 
								album.getName(), album.getDesc());
						//刷新显示数据
						reloadList();
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						// TODO Auto-generated method stub
						
					}
				});
				
				//保存到新点歌单中
				Button btnSave = (Button)save_list.findViewById(R.id.btnSave);
				btnSave.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if(etListName.getText().toString().equals("")){
							GlobalApplication.alert("请输入点歌单名称！");
							return ;
						}
						//保存点歌单信息
						Album album = new Album();
						if(currentKey!=null && !currentKey.equals("")){
							album.setId(currentKey);
						}
						
						album.setName(etListName.getText().toString());
						album.setDesc(etListDesc.getText().toString());
						album.setSongList(getSongList());
						GlobalApplication.getInstance().saveAsList(currentKey,album.getSongList(), 
								album.getName(), album.getDesc());
						//刷新显示数据
						reloadList();
						pop.dismiss();
					}
				});
				
				Button btnCancel = (Button)save_list.findViewById(R.id.btnCancel);
				btnCancel.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						pop.dismiss();
					}
				});
			}
		});
		
		mylist = (ListView)view.findViewById(R.id.mylist);
		
		
		//列表显示
		mySongAdapter = new MySongAdapter(getActivity());
		mySongAdapter.setSongList(main.getCurrentList());
		mylist.setAdapter(mySongAdapter);
		//点歌单
		array = new SongListGroupArray();
		ArrayList<SongList> songLists = new ArrayList<SongList>();
		for(Iterator<Album> it = main.getMySongList().iterator();it.hasNext();){
			Album album = (Album)it.next();
			songLists.add(new SongList(album.getId(),album.getName(),album.getDesc()));
		}
		//添加我的点歌单
		array.addMyList(songLists);
		
		songListAdapter = new SongListAdapter(getActivity(),array);
		final ExpandableListView listAll = (ExpandableListView)view.findViewById(R.id.listAll);
		listAll.setAdapter(songListAdapter);
		listAll.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				//设置当前标题为点歌单名称
				currentKey = array.getGroup(groupPosition).get(childPosition).getId();//临时保存key
				currentName = array.getGroup(groupPosition).get(childPosition).getName();
				currentDesc = array.getGroup(groupPosition).get(childPosition).getDesc();
				
				mainTitle.setText(currentName);
				editing = true;
				//加载当前选中的点歌单中的可见列表
				ArrayList<Song> songs = GlobalApplication.getInstance()
						.loadMySongList(main.getMySongList(), currentName);
				main.setCurrentList(songs);
				mySongAdapter.setSongList(songs);
				//收起所有展开的Group
				for(int i =0;i<array.getGroupCount();i++){
					listAll.collapseGroup(i);
				}
				return false;
			}
		});
		
		//长按列表的响应
		listAll.setOnCreateContextMenuListener(new ExpandableListView.OnCreateContextMenuListener() {
			
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo)menuInfo;
				//Group时，不弹出上下文菜单
				if(info.targetView.getId()==R.id.group_item){
					return;
				}
				
				menu.add(0,0,0,"删除当前点歌单");
				menu.add(0,1,0,"删除全部点歌单");
				menu.add(0,2,0,"取消");
			}
		});
		
		
		Button btnShare = (Button)view.findViewById(R.id.btnShare);
		Button btnClear = (Button)view.findViewById(R.id.btnClear);
		
		btnShare.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//弹出窗口，让用户选择要分享的点歌单
				
				
				if(main.getMySongList().size()==0){
					Toast.makeText(getActivity(), "哦，还没有点歌单哦，先建一个吧！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				if(GlobalApplication.getInstance().logined==false){
					Toast.makeText(getActivity(), "请先使用新浪微博帐号登录后再分享", Toast.LENGTH_SHORT).show();
					GlobalApplication.getMainActivity().getTabHost().setCurrentTab(2);
					return;
				}
				
				String[] albums = new String[main.getMySongList().size()];
				int i = 0;
				for(Iterator<Album> it = main.getMySongList().iterator();it.hasNext();){
					Album album = (Album)it.next();
					albums[i] = album.getName();
					i++;
				}
				
				AlertDialog.Builder builder = new Builder(GlobalApplication.activity);
				builder.setTitle("请选择要分享的点歌单")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setSingleChoiceItems(
						albums, 0,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								Album album = main.getMySongList().get(which);
								StringBuffer sharedText = new StringBuffer();
								sharedText.append("我分享了一个点歌单："+album.getName());
								
								sharedText.append("，看看这里 "+WeiboConstant.SHARED_URL);
								if(GlobalApplication.getMainActivity().getUserCenterFragment()!=null){
									UserCenterFragment ucf = (UserCenterFragment)GlobalApplication.getMainActivity().getUserCenterFragment();
									ucf.updateStatus(sharedText.toString());
									
									GlobalApplication.showProgress("分享点歌单", "正在分享我的点歌单....");
								}
								
								//如果用户登录了新浪微博，则保存数据到服务器端
								if(GlobalApplication.getInstance().logined){
									String params = GlobalApplication.getInstance().getParams(album.getSongList(), 
											album.getName(), album.getDesc());
									LoadDataAsynTask.loadDataFromUrl(GlobalApplication.saveListUrl, params,WeiboConstant.EXTERNAL_DIR_CACHE);
								}
								
								dialog.dismiss();
							}
						}).setNegativeButton("取消", null).show();
			}
		});
		
		final MyFragment fragment = this;
		btnClear.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mySongAdapter.getSongList()==null || mySongAdapter.getSongList().size()==0){
					Toast.makeText(getActivity(), "列表本来就是空的，没啥可清空的！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				CustomDialog dialog = DialogUtil.showCustomDialog(getActivity(),"要清空当前点歌单列表吗？", v, Gravity.BOTTOM);
				dialog.setOnOkClickListener(new CustomDialog.OkClickListener() {
					@Override
					public void onClick(View v) {
						dialogExecute(Constant.FUNC_CLEAR_LIST);
					}
				});
			}
		});
		
		
		return view;
	}
	
	
	//长按键弹出菜单的事件处理
	public boolean onContextItemSelected(MenuItem item) {
		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item
				.getMenuInfo();
		
		View view = info.targetView;
		
		switch(item.getItemId()){
		case 0:
			final TextView tvListName = (TextView)view.findViewById(R.id.tvListName);
			TextView tvKey = (TextView)view.findViewById(R.id.tvKey);
			CustomDialog dialog = DialogUtil.showCustomDialog(getActivity(),"要删除点歌单 " + tvListName.getText()+ " ？", 
					view, Gravity.BOTTOM);
			dialog.setOnOkClickListener(new CustomDialog.OkClickListener() {
				@Override
				public void onClick(View v) {
					dialogExecute(Constant.FUNC_DELETE_SONG_LIST,tvListName.getText());
				}
			});
			break;
		case 1:
			CustomDialog deleteAllDialog = DialogUtil.showCustomDialog(getActivity(),"要删除所有点歌单么 ？", 
					view, Gravity.BOTTOM);
			deleteAllDialog.setOnOkClickListener(new CustomDialog.OkClickListener() {
				@Override
				public void onClick(View v) {
					dialogExecute(Constant.FUNC_DELETE_ALL_LIST);
				}
			});
			break;
		case 2:
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	//对话框确认事件回调处理
	@Override
	public void dialogExecute(int funcId, Object...params) {
		switch(funcId){
		case Constant.FUNC_CLEAR_LIST:
			MainActivity main = (MainActivity)GlobalApplication.activity;
			main.clearMyList();
			mySongAdapter.setSongList(null);
			mySongAdapter.notifyDataSetChanged();
//			GlobalApplication.getInstance().clearList();
//			reloadList();
			break;
		case Constant.FUNC_DELETE_SONG_LIST:
			String albumName = (String)params[0];
			ArrayList<Album> albums = GlobalApplication.getInstance().loadMyAlbums();
			GlobalApplication.getInstance().removeMyAlbum(albums, albumName);
			reloadList();
			break;
		case Constant.FUNC_DELETE_ALL_LIST:
			ArrayList<Album> allAlbums = GlobalApplication.getInstance().loadMyAlbums();
			GlobalApplication.getInstance().removeAllAlbum(allAlbums);
			reloadList();
			break;
		}
	}
	


	@Override
	public void updateListView() {
		mySongAdapter.notifyDataSetChanged();
	}

	private OnDismissListener addDismissListener(){
		return new PopupWindow.OnDismissListener() {
			
			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	private ArrayList<Song> getSongList(){
		ArrayList<Song> list = new ArrayList<Song>();
		for(Iterator<Song> it=mySongAdapter.getSongList().iterator();it.hasNext();){
			Song song = it.next();
			list.add(song);
		}
		return list;
	}
	
	/*
	 * 刷新列表数据
	 */
	public void reloadList(){
		ArrayList<Album> albums = GlobalApplication.getInstance().loadMyAlbums();
		GlobalApplication.getMainActivity().setMySongList(albums);
		if(albums.size()>0){
			GlobalApplication.getMainActivity().setCurrentList(albums.get(0).getSongList());
		}
		
		array = new SongListGroupArray();
		ArrayList<SongList> songLists = new ArrayList<SongList>();
		for(Iterator<Album> it = GlobalApplication.getMainActivity().getMySongList().iterator();it.hasNext();){
			Album album = (Album)it.next();
			songLists.add(new SongList(album.getId(),album.getName(),album.getDesc()));
		}
		array.addMyList(songLists);
		songListAdapter.setSongListGroupArray(array);
		songListAdapter.notifyDataSetChanged();
	}

	public SongListAdapter getSongListAdapter() {
		return songListAdapter;
	}

	public void setSongListAdapter(SongListAdapter songListAdapter) {
		this.songListAdapter = songListAdapter;
	}

	public MySongAdapter getMySongAdapter() {
		return mySongAdapter;
	}

	public void setMySongAdapter(MySongAdapter mySongAdapter) {
		this.mySongAdapter = mySongAdapter;
	}


}
